package org.bozo.im.activity.account;

import java.util.ArrayList;

import org.bozo.im.R;
import org.bozo.im.common.types.Protocol;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ProtocolAdapter extends BaseAdapter {

	private Context mContext;
	private LayoutInflater mInflater;
	private ArrayList<Protocol> mProtocol;
	private AddAccountDialog mDialog;

	public ProtocolAdapter(Context pContext, AddAccountDialog pDialog) {
		mProtocol = new ArrayList<Protocol>();
		mContext = pContext;
		mDialog = pDialog;
	}

	public void updateProtocols(ArrayList<Protocol> pProtocol) {
		mProtocol = pProtocol;
		notifyDataSetChanged();
	}

	public int getCount() {
		return mProtocol.size();
	}

	public Object getItem(int pPosition) {
		return mProtocol.get(pPosition);
	}

	public long getItemId(int pPosition) {
		return mProtocol.get(pPosition).hashCode();
	}

	public View getView(int pPosition, View pConvertView, ViewGroup pParent) {

		View lView = pConvertView;

		if (mInflater == null)
			mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		Protocol lProtocol = (Protocol)getItem(pPosition);
		ProtocolHolder lHolder;

		if (lView == null) {

			if (pParent == mDialog.findViewById(R.id.protocol)) {
				lView = mInflater.inflate(R.layout.protocol_item, null);
			} else {			
				lView = mInflater.inflate(R.layout.full_protocol_item, null);
			}
			
			lHolder = new ProtocolHolder();

			lHolder.protocol_icon = (ImageView)lView.findViewById(R.id.protocol_icon);
			lHolder.protocol = (TextView)lView.findViewById(R.id.protocol);

			lView.setTag(lHolder);
		} else {
			lHolder = (ProtocolHolder)lView.getTag();
		}

		if (lProtocol != null) {
			lHolder.protocol.setText(mContext.getResources().getString(lProtocol.getRessourceId()));
				
			if (lHolder.protocol_icon != null)
				lHolder.protocol_icon.setImageResource(lProtocol.getImageId());
		}

		return lView;
	}

	private static class ProtocolHolder {
		ImageView protocol_icon;
		TextView protocol;
	}
}
